<route lang="json5">
{
  style: {
    navigationBarTitleText: '拼团',
    navigationStyle: 'default',
  },
}
</route>
<template>
  <view class="product-detail-page bg-gray-50 min-h-screen pb-20">
    <wd-swiper :list="product.images" :height="375"></wd-swiper>

    <view class="px-4 py-4 bg-white">
      <view class="flex justify-between items-center mb-2">
        <view class="text-orange-500 font-bold">
          <text class="text-sm">¥</text>
          <text class="text-2xl" v-if="product?.isSpell == 1">{{ product?.vipPrice }}</text>
          <text class="text-2xl" v-else-if="product?.isSpell == 2">{{ product?.spellPrice }}</text>
          <text class="ml-1 text-xs font-normal line-through text-gray-500">
            ¥{{ product?.price }}
          </text>
        </view>
        <view class="flex items-center text-gray-500 text-sm">
          <i class="iconfont icon-gouwuche w-4 leading-4 mr-1"></i>
          <text>已售 {{ product?.sales }}</text>
        </view>
      </view>

      <view class="text-lg font-medium text-gray-800 line-clamp-3 mb-4">{{ product?.name }}</view>

      <view class="flex flex-wrap gap-2 mb-4">
        <text class="px-2 py-1 bg-orange-50 text-orange-500 text-xs rounded-md">
          {{ product?.keyword }}
        </text>
      </view>
    </view>

    <!-- 在拼订单 -->
    <view class="p-4 bg-white rounded shaodw mt-2" v-if="waitOrderList.length > 0">
      <view class="font-medium text-gray-800 mb-3">
        等待成团
        <text class="text-[#ff6a33] text-xs">{{ waitOrderList.length }}人在抢</text>
      </view>

      <scroll-view scroll-y class="h-20">
        <!-- 订单列表 -->
        <view class="bb flex justify-between px-2 mb-2 py-1" v-for="order in waitOrderList" :key="order.id">
          <view class="flex w-20 flex-1 justify-start items-center">
            <image :src="order.userImage" class="w-5 h-5 mr-2" mode="scaleToFill" />
            <text>{{ order.userName }}</text>
          </view>
          <view class="pay-button" @click="() => showPopup(order.id)">
            <text class="pay-text">立即成团</text>
          </view>
        </view>
      </scroll-view>
    </view>

    <view class="px-4 py-4 bg-white mt-2" v-if="store" @click="navigateTo('/pages/store/detail?id=' + store.id)">
      <view class="flex items-center justify-between">
        <view class="flex items-center">
          <image :src="store?.picture" alt="Shop avatar" class="w-12 h-12 rounded-full object-cover mr-3" />
          <view>
            <view class="font-medium text-gray-800">{{ store?.name }}</view>
            <view class="text-xs text-gray-500">{{ store?.address }}</view>
          </view>
        </view>
        <view class="flex gap-2">
          <view class="w-10 h-10 rounded-full bg-orange-50 flex items-center justify-center text-orange-500"
            @click.stop="callShop">
            <i class="iconfont icon-dianhua w-5 h-5"></i>
          </view>
          <view class="w-10 h-10 rounded-full bg-orange-50 flex items-center justify-center text-orange-500"
            @click.stop="navigateToShop">
            <i class="iconfont icon-zuobiao w-5 h-5"></i>
          </view>
        </view>
      </view>
    </view>

    <wd-tabs class="mt-2">
      <wd-tab title="商品详情">
        <view class="px-4 py-4 bg-white">
          <view class="rich-text-content" v-html="product.info"></view>
        </view>
      </wd-tab>

      <wd-tab title="用户评价">
        <view class="px-4 py-4 bg-white flex flex-col">
          <wd-status-tip image="content" tip="暂无内容" v-if="newsList.length == 0" />
          <!-- 评价列表 -->
          <view class="bg-white rounded-lg shadow overflow-hidden p-2 mb-2" v-for="news in newsList" :key="news.id">
            <view class="flex flex-row mt-2 items-center">
              <image :src="news.userImage" class="w-8 h-8 rounded-full mr-3 shadow" mode="scaleToFill" />
              <text class="text-xs">{{ news.userName }}</text>
            </view>

            <view class="font-medium text-gray-800 text-xs line-clamp-2 my-4">
              评价：{{ news.evaluationContent }}
            </view>
            <view class="grid grid-cols-3 gap-2 my-2">
              <image v-for="(image, imgIndex) in parseImageList(news)" :key="imgIndex" :src="image"
                :alt="`Image ${imgIndex}`" class="w-full h-20 object-cover rounded bg-slate-50" />
            </view>
            <view class="flex items-center justify-between mt-2 mb-2">
              <text class="flex-1 text-xs text-gray-500">
                用户评分：
                <!-- <text class="text-[#ff6a33]">{{ news.evaluationStar }}</text> -->
                <wd-rate v-model="news.evaluationStar" />
              </text>
              <text class="text-xs text-gray-500">{{ news.addTime }}</text>
            </view>
          </view>

          <!-- 更多按钮 -->
          <view class="w-full text-center text-xs mt-2" @click="loadmore">查看更多</view>
        </view>
      </wd-tab>
    </wd-tabs>

    <view class="px-4 py-4 bg-white mt-2">
      <view class="font-medium text-gray-800 mb-3">猜你喜欢</view>
      <view class="grid grid-cols-2 gap-3">
        <view v-for="(item, index) in recommendations" :key="index" @click="toProductDetail(item.id)"
          class="bg-gray-50 rounded-lg overflow-hidden">
          <image :src="item.image" :alt="item.name" class="w-full h-32 object-cover" />
          <view class="p-2">
            <view class="text-sm text-gray-800 line-clamp-2">{{ item.name }}</view>
            <view class="text-orange-500 font-bold text-sm mt-1" v-if="item.isSpell == 1">
              ¥{{ item.vipPrice }}
              <text class="ml-1 text-xs font-normal line-through text-gray-500">
                ¥{{ item.price }}
              </text>
            </view>
            <view class="text-orange-500 font-bold text-sm mt-1" v-if="item.isSpell == 2">
              ¥{{ item?.spellPrice }}
              <text class="ml-1 text-xs font-normal line-through text-gray-500">
                ¥{{ item?.price }}
              </text>
            </view>
          </view>
        </view>
      </view>
    </view>

    <view class="fixed bottom-0 left-0 right-0 bg-white border-t border-gray-200 px-4 py-3 flex items-center">
      <wd-button type="icon" icon="share"
        class="bg-gray-100 text-3 flex items-center justify-center text-gray-500! mr-3" v-show="shareBtnShow"
        @click="openShareModal"></wd-button>

      <view class="flex-1 bg-orange-500 text-white font-bold py-3 px-4 rounded-lg flex items-center justify-center"
        @click="() => showPopup()">
        立即拼团 ¥{{ product?.isSpell == 1 ? product?.vipPrice : product?.spellPrice }}
      </view>
    </view>

    <GroupSubmit ref="groupSubmitRef" :visible="popupVisible" @close="hidePopup" @pay="handlePayment" />

    <wd-popup v-model="mapShow">
      <view class="p-2 flex justify-between items-center flex-col">
        <text class="text-lg font-bold text-gray-800 mb-1">{{ store?.name }}</text>
        <text class="text-xs text-gray-800 mb-1">{{ store?.address }}</text>
        <image :src="src" class="w-80 h-80" mode="scaleToFill" />
        <view class="mt-1 flex justify-center items-center bg-orange w-30 h-10 rounded-20 text-white" @click="toMap">
          <i class="iconfont icon-zuobiao w-5 text-3"></i>
          导航
        </view>
      </view>
    </wd-popup>

    <!-- 分享 -->
    <wd-popup v-model="shareShow">
      <cc-poster v-if="shareShow" @success="posterSuccess" :imgSrc="product.image" :QrSrc="erweimapath"
        :Title="product.name" :PriceTxt="product.isSpell == 2 ? product?.spellPrice : product?.vipPrice"
        :LineType="false"></cc-poster>
      <view class="w-650rpx flex justify-center items-center mb-24rpx">
        <wd-button type="primary" @click="shareFriend">分享好友</wd-button>
        <wd-button type="primary" @click="save">保存</wd-button>
      </view>
    </wd-popup>
  </view>
</template>

<script setup>
import { ref, onMounted, onUnmounted, computed } from 'vue'
import GroupSubmit from '@/components/groupSubmit.vue'
import { http } from '@/utils/http'
import { useUserStore } from '@/store/user'
import { useInviteStore } from '@/store/invite'

import dayjs from 'dayjs'
import { useOrderStore } from '@/store/order'

const orderStore = useOrderStore()

const product = ref({
  image: '',
  sliderImage: '',
  images: [],
})

const orderForm = ref({
  content: '',
  images: '',
  name: '',
  phone: '',
  detailedAddress: '',
  upperTime: '',
})

const newsList = ref([])
const waitOrderList = ref([])

const getProduct = async (id) => {
  let res = await http.get('/api/home/productDetails', { id })
  if (res.code == 200) {
    let arr = []
    arr.push(res.data.product.image)
    if (res.data.product.sliderImage) {
      arr = arr.concat(res.data.product.sliderImage.split(','))
    }
    let info = res.data.product.info.replace(/<img/g, '<img style="width:100%;height:auto"')
    product.value = { ...res.data.product, images: arr, info }
    if (product.value.storeId) {
      getStore()
    }
  }

  // 获取评论
  let resp = await http.get('/api/evaluate/list', {
    pid: product.value.id,
    pageNum: 1,
    pageSize: 2,
  })
  if (resp.code == 200) {
    console.log('resp', resp)
    newsList.value = resp.data.list
  }

  //   在拼订单查询
  let respe = await http.get('/api/groupOrder/list', {
    productId: product.value.id,
    status: 1,
  })

  if (respe.code == 200) {
    waitOrderList.value = respe.data.list
  }
}

const navigateTo = (url) => {
  uni.navigateTo({ url })
}

const loadmore = () => {
  uni.navigateTo({ url: '/pages/product/evaluation?id=' + product.value.id })
}

const store = ref(null)

const getStore = async (id) => {
  let res = await http.get('/api/store/details', { id: product.value.storeId })
  if (res.code == 200) {
    store.value = res.data.store
  }
}

const inviteStore = useInviteStore()

onLoad((option) => {
  // #ifdef MP-WEIXIN
  let scene = decodeURIComponent(option.scene)
  console.log('scene', scene)
  if (scene) {
    let params = scene.split('-')

    console.log('params', params)


    let id = params[0]
    let code = ''

    if (params.length == 2) {
      code = params[1]
      inviteStore.push(id, code)
    }


    getProduct(id)
    getRecommend()
  }
  // #endif
  // #ifndef MP-WEIXIN
  if (option.id && option.invitationCode) {
    inviteStore.push(option.id, option.invitationCode)
  }
  getProduct(option.id)
  getRecommend()
  // #endif

})

const toProductDetail = (id) => {
  uni.navigateTo({ url: '/pages/product/detail?scene=' + id })
}

const recommendations = ref([])

const getRecommend = async () => {
  let res = await http.get('/api/home/recommend')
  if (res.code == 200) {
    recommendations.value = res.data.products
  }
}

const popupVisible = ref(false)

const groupSubmitRef = ref(null)

const showPopup = (orderId) => {
  console.log('%c [ orderId ]-330', 'font-size:13px; background:pink; color:#bf2c9f;', orderId)

  orderStore.goodsInfo = product.value
  orderStore.num = 1

  if (orderId) {
    groupSubmitRef.value.groupId = orderId
  }

  popupVisible.value = true
}

const hidePopup = () => {
  popupVisible.value = false
}

const handlePayment = (paymentData) => {
  // 处理支付逻辑
  uni.showToast({
    title: '支付成功',
    icon: 'success',
  })

  // hidePopup()
  getProduct(product.value.id)
}

// Purchase modal state
const quantity = ref(1)

const confirmPurchase = async () => {
  let share = inviteStore.fineInviteCode(product.value.id)

  let data = {
    id: product.value.id,
    number: quantity.value,
    remark: '',
    orderType: 1,
    groupId: 0,
    couponId: 0,
    share,
  }

  if (product.value.type == 1) {
    data = {
      ...data,
      ...orderForm.value,
      orderType: 3,
    }
  }

  let res = await http({
    url: '/api/wxPayApplet/productWxPay',
    method: 'POST',
    data: data,
  })

  if (res.code == 200) {
    uni.requestPayment({
      provider: 'wxpay',
      timeStamp: res.data.timeStamp,
      nonceStr: res.data.nonceStr,
      package: res.data.package,
      signType: 'MD5',
      paySign: res.data.paySign,
      success: (res) => {
        uni.showToast({
          title: '支付成功',
          icon: 'success',
        })
        closePurchaseModal()
      },
      fail: (err) => {
        uni.showToast({
          title: '支付失败',
          icon: 'none',
        })
      },
    })
  }
}

const userStore = useUserStore()
const erweimapath = ref('')
const shareShow = ref(false)
const imgBase = ref('')

const shareBtnShow = computed(() => userStore.token != '' || userStore.token != null)

const openShareModal = async () => {
  // if (!shareBtnShow.value) {
  //   uni.showToast({ title: '分享请先登录', icon: 'none' })
  //   return
  // }

  let res = await http.get('/api/file/qrcode', {
    id: product.value.id,
    invitationCode: userStore?.userInfo?.invitationCode,
    page: 'pages/group/product',
  })

  if (res.code == 200) {
    erweimapath.value = res.data
    shareShow.value = true
  }
}

const posterSuccess = ({ tempFilePath }) => {
  imgBase.value = tempFilePath
}

const shareFriend = () => {
  if (!imgBase.value) {
    uni.showToast({ title: '请先生成分享图', icon: 'none' })
    return
  }

  wx.showShareImageMenu({
    path: imgBase.value,
  })

  shareShow.value = false
}

// onReady(() => {
//   uni.onShareAppMessage(() => {
//     return {
//       title: product.value.name,
//       path: `/pages/product/detail?scene=${product.value.id}-${userStore?.userInfo?.invitationCode}`,
//       imageUrl: imgBase.value,
//     }
//   })
// })

onShareAppMessage(() => {
  return {
    title: product.value.name,
    path: `/pages/product/detail?scene=${product.value.id}-${userStore?.userInfo?.invitationCode}`,
    // imageUrl: imgBase.value,
  }
})

onShareTimeline(() => {
  return {
    title: product.value.name,
    path: `/pages/product/detail?scene=${product.value.id}-${userStore?.userInfo?.invitationCode}`,
    // imageUrl: imgBase.value,
  }
})

const save = () => {
  if (!imgBase.value) {
    uni.showToast({ title: '请先生成分享图', icon: 'none' })
    return
  }

  shareShow.value = false

  uni.authorize({
    scope: 'scope.writePhotosAlbum',
    success: () => {
      uni.saveImageToPhotosAlbum({
        filePath: imgBase.value,
        success: () => {
          uni.showToast({ title: '保存成功', icon: 'success' })
        },
        fail: (err) => {
          console.error('保存失败', err)
          uni.showToast({ title: '保存失败，请重试', icon: 'none' })
        },
      })
    },
    fail: () => {
      uni.showToast({
        title: '需要相册权限',
        icon: 'none',
        duration: 3000,
      })
    },
  })
}

// Actions
const goBack = () => {
  uni.navigateBack()
}

const callShop = () => {
  uni.makePhoneCall({
    phoneNumber: store.value.telephone,
  })
}

const mapShow = ref(false)
const src = ref('')

const navigateToShop = () => {
  // 根据店铺定位打开地图

  let longitude = store.value.longitude
  let dimension = store.value.dimension

  src.value = `https://restapi.amap.com/v3/staticmap?key=fbacb26edf56429309b33c7ed0e37d0b&location=${longitude},${dimension}&zoom=17&markers=mid,0xFF0000,A:${longitude},${dimension}`
  mapShow.value = true
}

const toMap = () => {
  let longitude = store.value.longitude
  let dimension = store.value.dimension
  let storeName = store.value.name
  let address = store.value.address

  uni.navigateTo({
    url:
      '/pages/web/map?longitude=' +
      longitude +
      '&dimension=' +
      dimension +
      '&storeName=' +
      storeName +
      '&address=' +
      address,
  })
}

const shareProduct = () => {
  openShareModal()
}

const parseImageList = (news) => {
  return news.evaluationImage.split(',')
}
</script>

<style scoped>
.carousel-container {
  width: 100%;
}

.carousel-slide {
  width: 100%;
}

.line-clamp-2 {
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.line-clamp-3 {
  display: -webkit-box;
  -webkit-line-clamp: 3;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.translate-y-full {
  transform: translateY(100%);
}

.translate-y-0 {
  transform: translateY(0);
}

:deep(.rich-text-content) {
  line-height: 1.6;
}

:deep(.rich-text-content image) {
  max-width: 100%;
  height: auto;
  margin: 1rem 0;
  border-radius: 0.5rem;
}

:deep(.rich-text-content h4) {
  margin-top: 1.5rem;
  margin-bottom: 0.75rem;
  font-size: 1.125rem;
  font-weight: bold;
}

:deep(.rich-text-content p) {
  margin-bottom: 0.75rem;
}

:deep(.rich-text-content strong) {
  font-weight: bold;
}

.pay-button {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 40rpx;
  padding: 12rpx;
  background-color: #07c160;
  border-radius: 8rpx;
}

.pay-text {
  font-size: 24rpx;
  font-weight: 500;
  color: white;
}
</style>
